import boto3
import datetime

import json
import traceback
client = boto3.client('events')

global_parameters = {
    "enableNotification": True,
    "source": "pt.spider",
    "detailType": "Spider State-change Notification",
    "metadata": {}
}


def processRequest(messageList, event, context):
    raise NotImplementedError("processRequest not implemented")


def _extract_message(record):
    eventSourceArn = record["eventSourceARN"]
    queueName = eventSourceArn.split(":")[-1]
    messageBodyText = record.get("body")
    message = {
        "receiptHandle": record.get("receiptHandle"),
        "messageBodyText": messageBodyText,
        "metadata": {
            "eventSource": record.get("eventSource"),
            "eventSourceARN": record.get("eventSourceARN"),
            "queueName": queueName,
            "senderId": record.get("attributes").get("SenderId"),
            "approximateFirstReceiveTimestamp": record.get("attributes").get("ApproximateFirstReceiveTimestamp"),
            "approximateReceiveCount": record.get("attributes").get("ApproximateReceiveCount"),
            "sentTimestamp": record.get("attributes").get("SentTimestamp"),
        }
    }
    return message


def handler(event, context):
    print("triggered by QueueHandler...")
    print("event is %s" % event)
    try:
        messageList = [_extract_message(r) for r in event["Records"]]

        respDict = processRequest(messageList, event, context)
        if respDict and not isinstance(respDict, dict):
            raise Exception("resp type must be dict, now is %s" % type(respDict))

        if global_parameters["enableNotification"]:
            entries = [{
                    "Source": global_parameters["source"],
                    "DetailType": global_parameters["detailType"],
                    "Detail": json.dumps({
                        "state": "COMPLETED",
                        "result": "SUCCESS",
                        "metadata": global_parameters.get("metadata", {}),
                        "payload": respDict
                    }),
                    "Resources": [],
                    "Time": datetime.datetime.now()
                }]
            print("putting success event to EventBus, event detail is %s..." % entries)
            response = client.put_events(
                Entries=entries
            )
            print("put success event to EventBus")
    except Exception as ex:
        traceback.print_exc()
        if global_parameters["enableNotification"]:
            entries = [{
                    "Source": global_parameters["source"],
                    "DetailType": global_parameters["detailType"],
                    "Detail": json.dumps({
                        "state": "COMPLETED",
                        "result": "ERROR",
                        "metadata": global_parameters.get("metadata", {}),
                        "payload": repr(ex)
                    }),
                    "Resources": [],
                    "Time": datetime.datetime.now()
                }]
            print("putting error event to EventBus, event detail is %s..." % entries)
            response = client.put_events(
                Entries=entries
            )
            print("put error event to EventBus")